use macroquad::prelude::ImageFormat;
use macroquad::prelude::Texture2D;

use crate::api::ApiPost;
use crate::client::request_texture;

pub struct User {
    pub finger: String,
    pub avatar: Texture2D,
    pub avatar_link: String,
}

impl User {
    pub async fn request_texture(&mut self) {
        self.avatar = request_texture(&self.avatar_link).unwrap_or_else(|_| no_avatar());
    }
}

pub struct UserCache {
    users: Vec<User>,
}

impl UserCache {
    pub fn find_finger(&self, finger: &str) -> Option<&User> {
        for u in self.users.iter() {
            if u.finger == finger {
                return Some(&u);
            }
        }
        return None;
    }
    pub fn finger_exists(&self, finger: &str) -> bool {
        return self.find_finger(finger).is_some();
    }
    pub fn from_apiposts(posts: &Vec<ApiPost>) -> Self {
        let mut res = UserCache { users: vec![] };
        for p in posts {
            let acc = &p.account;
            if !res.finger_exists(&acc.acct) {
                res.users.push(User {
                    finger: acc.acct.clone(),
                    avatar: no_avatar(),
                    avatar_link: acc.avatar_static.clone(),
                })
            }
        }
        return res;
    }
}

fn no_avatar() -> Texture2D {
    Texture2D::from_file_with_format(include_bytes!("../no_avatar.png"), Some(ImageFormat::Png))
}
